import os
import sys
from datetime import datetime

import bencode

from logger import Logger
from util import rename_file

sys.stdout = Logger(datetime.now().strftime("log/%Y%m%d_%H%M%S") + ".txt")


def get_torrent_name(torrent_file_path):
    # 读取.torrent文件
    with open(torrent_file_path, 'rb') as file:
        torrent_data = file.read()

    # 解码Bencode数据
    decoded_data = bencode.bdecode(torrent_data)
    single_file_name = decoded_data['info']['name']

    if type(decoded_data['info']['name']) == bytes:
        byte_data = decoded_data['info']['name']
        try:
            text_big5 = byte_data.decode('big5')
            print("Big5 解码结果:", text_big5)
            return text_big5
        except UnicodeDecodeError as e:
            print("Big5 解码失败:", e)
        # 尝试 GBK 编码 (兼容 GB2312，常见于简体中文)
        try:
            text_gbk = byte_data.decode('gbk')
            print("GBK 解码结果:", text_gbk)
            return text_gbk
        except UnicodeDecodeError as e:
            print("GBK 解码失败:", e)
        # 尝试 UTF-8 编码
        try:
            text_utf8 = byte_data.decode('utf-8')
            print("UTF-8 解码结果:", text_utf8)
            return text_utf8
        except UnicodeDecodeError as e:
            print("UTF-8 解码失败:", e)
    else:
        return single_file_name


def get_torrent_files(torrent_file_path):
    # 读取.torrent文件
    with open(torrent_file_path, 'rb') as file:
        torrent_data = file.read()

    # 解码Bencode数据
    decoded_data = bencode.bdecode(torrent_data)

    # 获取文件列表
    files = decoded_data['info']['files']
    if files:
        # files是一个列表，其中包含字典，每个字典代表一个文件
        file_names = []
        for file_info in files:
            # 每个文件信息是一个字典，其中'length'是文件大小，'path'是文件路径
            file_path = file_info['path']
            # 将路径列表中的每个元素解码成字符串，并用'/'连接起来
            file_name = '/'.join(file_path)
            file_names.append(file_name)
        return file_names
    else:
        # 如果没有文件列表，只有一个文件
        single_file_name = decoded_data['info']['name']
        return [single_file_name]


if __name__ == "__main__":
    base_path_list = [
        # r"E:\torrents_collector\movies",
        # r"E:\torrents_collector\tvs",
        # r"E:\torrents_collector\otvs",
        r"E:\torrents_collector\games_fitgirl_tmp",
    ]
    # base_path = "E:/torrents_collector/movies"

    for base_path in base_path_list:
        for root, dirs, files in os.walk(base_path):
            for file in files:
                try:
                    # 检查文件扩展名是否为.json
                    if file.endswith('.torrent'):
                        print(f'processing {file}')
                        # 构造完整的文件路径
                        file_path = os.path.join(root, file)
                        torrent_name = get_torrent_name(file_path)
                        rename_file(file_path, torrent_name)
                        print(f'renamed to {torrent_name}')
                except Exception as ex:
                    print(f"error: {ex}")

# 使用函数
# torrent_file_path = 'F4DB14B68D66F48307B9FCD21A7392A6E42CDF06.torrent'
# torrent_name = get_torrent_name(torrent_file_path)
# print(f'{torrent_name}')
# rename_file(torrent_file_path, torrent_name)
# file_names = get_torrent_files(torrent_file_path)
# for name in file_names:
#     print(name)